// pages/eventdetail/eventdetail.js
var util = require("../../utils/util.js")
const {
  $Message
} = require('../../iview/base/index');

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttontext: "去报名",
    buttoncolor:"yellow",
    eventstate: "" ,
    feed:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      eventid: options.id
    })
    wx.setNavigationBarTitle({
      title: '活动详情',
    })
    const app = getApp()
    console.log(app.globalData.openID)
    /* 读数据库 */
    const db = wx.cloud.database()
    const eventcol = db.collection("event")
    const clubcol = db.collection("club")
    var that = this
    var _hot = 0
    var date = new Date()
    eventcol.where({
      _id: options.id
    }).get().then(function (e) {
      var count = e.data[0].count + 1
      var _hot = 0
      var date = new Date()
      var hours = Math.ceil((date.getTime() - e.data[0].publishtime) / 3600000)
      if (count > 0) {
        _hot = (count-1) / (hours + 2)
      }
      wx.cloud.callFunction({
        name: 'search',
        data: {
          eventid: options.id,
          hot:_hot
        }
      }).catch(function (err) {
        console.log(err)
      })
    })
    eventcol.where({
      _id: options.id
    }).get().then((res) => {
      res.data[0].fmttimefrom = util.formatTime(res.data[0].timefrom)
      res.data[0].fmttimeto = util.formatTime(res.data[0].timeto)
      that.setData({
        event: res.data[0]
      })
      /* 计算当前的报名状态 */
      var date = new Date();
      if (date < res.data[0].timefrom) { //活动开始前
        if (res.data[0].participants != undefined) { //存在这个数组
          console.log(res.data[0].participants)
          console.log(res.data[0].participants.indexOf(app.globalData.openID))
          if (res.data[0].participants.indexOf(app.globalData.openID) == -1) { //我不在里面就
            this.setData({
              buttontext: "去报名",
              buttoncolor:"yellow"
            })
          } else { //我在里面的话就
            this.setData({
              buttontext: "已报名",
              buttoncolor:"green"
            })
          }
        }
      } else { //活动已开始,视为已结束
        var fb = res.data[0].feedback
        that.setData({
          feedback: res.data[0].feedback
        })
        var total = 0
        var count = 0
        var already=false
        for (var i = 0; i < fb.length; i++) {
          if (fb[i] != undefined) {
            total += fb[i].score
            count += 1
            if(fb[i].participant==app.globalData.openID){   //若我评价过就设置already为true
              already=true
            }
          }
        }
        that.setData({
          average: total / count
        })
        if (res.data[0].participants != undefined && res.data[0].participants.indexOf(app.globalData.openID) != -1 && !already) { //如果活动结束而且我参加了活动且没有评价过
          this.setData({
            buttontext: "去评价",
            buttoncolor:"blue",
            feed:true
          })
        } else {
          this.setData({
            buttontext: "已结束",
            buttoncolor:"grey",
            feed:true
          })
        }
      }
      clubcol.where({
        _id: res.data[0].host
      }).get().then((res2) => {
        that.setData({
          club: res2.data[0]
        })
      })
    })
  },

  GotoClub: function(e) {
    var that = this
    wx.navigateTo({
      url: '/pages/clubprofile/clubprofile?id=' + that.data.event.host + '&userOpenId=' + app.globalData.openID,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  signUp: function(e) {
    var that = this
    var temp
    if (this.data.buttontext == '去报名') {
      //做两件事：1、把自己放进event的participants里
      //         2、把event放进自己的events里
      const db = wx.cloud.database()
      db.collection("event").where({
        _id: that.data.eventid
      }).get().then(
        function(eve) {
          console.log(eve)
          if (eve.data[0].participants == undefined) {
            temp = [app.globalData.openID]
          } else {
            temp = eve.data[0].participants
            temp.push(app.globalData.openID)
          }
        }
      ).then(function(arrOK) {
        console.log(temp)
        wx.cloud.callFunction({
          name: 'signUp',
          data: {
            participants: temp,
            id: that.data.eventid
          }
        }).then(function(suc) {
          $Message({
            content: '报名成功',
            type: "success"
          })
        })
      })
      //2、把event放进自己的events里
      var temp
      db.collection("user").where({
        _openid: app.globalData.openID
      }).get().then(function(e) {
        console.log(e)
        if (e.data[0].myevents == undefined) {
          temp = [{
            event_id: that.data.eventid,
            score: 0
          }]
        } else {
          temp = e.data[0].myevents
          temp.push({
            event_id: that.data.eventid,
            score: 0
          })
        }
      }).then(function(my) {
        wx.cloud.callFunction({
          name: "signUpMy",
          data: {
            myeve: temp
          }
        })
      })
    } else if (that.data.buttontext=='去评价'){
      wx.navigateTo({
        url: '/pages/evaluateevent/evaluateevent?id=' + that.data.eventid,
      })
    }else    
     {
      $Message({
        content: '活动已结束或不能重复报名',
        type: "default"
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})